package com.bj58.wuxian.lucene.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.bj58.wuxian.lucene.highlighter.HighlighterWrapper;
import com.bj58.wuxian.lucene.utils.LuceneUtil;

public class FileIndex {

	String path = "D:\\data";

	private Analyzer analyzer;
	Directory directory;

	private void index(String path) {
		List<File> fileList = new ArrayList<File>();
		fileList = getFileListByPath(path, fileList);
		IndexWriter indexWriter = LuceneUtil.getIndexWriter(directory, analyzer);

		try {
			for (Iterator<File> iterator = fileList.iterator(); iterator.hasNext();) {
				File file = (File) iterator.next();
				String line = FileUtils.readFileToString(file, "gbk");
				Document doc = new Document();
				doc.add(new TextField("filename", file.getName().substring(0, file.getName().lastIndexOf(".")),
						Store.YES));
				doc.add(new TextField("content", line, Store.YES));
				indexWriter.addDocument(doc);
			}
			indexWriter.commit();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void search(String filedName, String text) {
		Directory directory = LuceneUtil.getDirectory(path + "\\index");
		Analyzer analyzer = new IKAnalyzer(true);
		QueryParser queryParser = new QueryParser(filedName, analyzer);
		try {
			Query query = queryParser.parse(text);
			HighlighterWrapper.search(directory, analyzer, query, filedName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List<File> getFileListByPath(String path, List<File> fileList) {
		File file = new File(path);
		if (file.isDirectory() && !file.getName().equals("index")) {
			File[] files = file.listFiles();
			for (File f : files) {
				getFileListByPath(f.getAbsolutePath(), fileList);
			}
		} else if (file.isFile() && !file.isHidden() && !file.getName().endsWith(".pdf")) {
			fileList.add(file);
		}
		return fileList;
	}

	public void init() {
		analyzer = new IKAnalyzer(true);
		directory = LuceneUtil.getDirectory(path + "\\index");
	}

	@Test
	public void test() throws IOException {
		// index(path);
		search("content", "父亲");

	}

}
